<template>
  <div>

    <n-grid x-gap="12">
      <n-gi :span="12">
        <n-space style="margin-bottom: 10px">
          <n-h4 v-if="videoTextList.length > 0">视频时长: <n-gradient-text>{{videoTextList[videoTextList.length - 1].endTime}}</n-gradient-text>秒</n-h4>
          <n-h4  v-if="videoTextList.length > 0">分镜数量：<n-gradient-text>{{videoTextList.length}}</n-gradient-text>个</n-h4>
          <n-divider vertical></n-divider>
          <n-input-group>
<!--            <n-input-group-label size="small">每</n-input-group-label>-->
<!--            <n-input-number size="small" :style="{ width: '80px' }" v-model:value="mergeSeconds" :min="2" :max="10"/>-->
<!--            <n-input-group-label size="small">秒</n-input-group-label>-->
<!--            <n-input-group-label size="small">使用</n-input-group-label>-->
<!--            <n-select size="small" :style="{width: '80px'}" :options="mergeStringOption" v-model:value="mergeString"></n-select>-->
            <n-button size="small" type="primary" style="margin-left: 5px;" @click="boardTextMerge('merge')" :loading="mergeLoading">
              GPT改写
            </n-button>
          </n-input-group>
          <n-button size="small" type="info" @click="boardTextMerge" :loading="mergeLoading">
            原文使用
          </n-button>
        </n-space>
        <n-data-table
            :single-line="false"
            :columns="createColumns"
            :data="videoTextList"
            :loading="tableLoading"
            :style="{ height: `${clientHeight - 165}px` }"
            flex-height
        />
      </n-gi>
      <n-gi :span="12" v-if="videoTextListMerge.length > 0">
        <n-space style="margin-bottom: 10px">
          <n-h4> 合并结果 </n-h4>
          <n-h4  v-if="videoTextListMerge.length > 0">分镜数量：<n-gradient-text>{{videoTextListMerge.length}}</n-gradient-text>个</n-h4>
          <n-button v-if="videoTextListMerge.length > 0" size="small" type="primary" style="margin-left: 5px;" :loading="initializationLoading" @click="initialization">
            保存结果
          </n-button>
        </n-space>
          <n-data-table
              v-model:checked-row-keys="checkedRowKeys"
              :single-line="false"
              :columns="createColumns"
              :data="videoTextListMerge"
              :loading="tableLoading"
              :style="{ height: `${clientHeight - 165}px` }"
              flex-height
          />
      </n-gi>
    </n-grid>
  </div>
</template>
<script setup lang="ts">
import {NButton,useMessage} from 'naive-ui'
import {onMounted, ref} from "vue";
import {storyController} from "@/api/story/story.api"
import {storyBoardController} from "@/api/controller/story/storyBoard.api"
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"

const message = useMessage()
const story = ref("")
const tableLoading = ref(false)
const videoTextList = ref([])
const checkedRowKeys = ref([0])
const videoTextListMerge = ref([])
const mergeSeconds = ref(5)
const mergeString = ref(" ")
const mergeLoading = ref(false)
const initializationLoading = ref(false)
const isChange = ref(false)
const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const mergeStringOption = [
  {
    value: ',',
    label: '逗号'
  },{
    label: '空格',
    value: ' '
  }
]

const props = defineProps({
  story: {
    type: Object,
    required: true
  }
})

// 列表字段
const createColumns = [
  {
    title: '开始时间(秒)',
    key: 'startTime',
    width: 150,
    onclick: (row: any) => {
      console.log(row)
    }
  },
  {
    title: '结束时间(秒)',
    key: 'endTime',
    width: 150,
  },
  {
    title: '文本内容',
    key: 'content'
  }
]

onMounted(() => {
  getWhisperText()
  getVideoText()
})

const getWhisperText = () =>{
  tableLoading.value = true
  storyController.getWhisperText(props.story.id).then(res => {
    if (res.code === 200) {
      videoTextList.value = res.data
      videoTextList.value.forEach((item: any, index) => {
        item.key = index
      })
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

const getVideoText = () => {
  tableLoading.value = true
  storyController.getVideoText(props.story.id).then(res => {
    if (res.code === 200) {
      videoTextListMerge.value = res.data
      videoTextListMerge.value.forEach((item: any, index) => {
        item.key = index
      })
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

const nextStep = async (callback: any) => {
  if(isChange.value){
    window.$dialog.warning({
      title: "温馨提醒",
      content: "你重新编排后的分镜还未保存，是否需要保存？",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
         initialization()
         callback(true)
      },
      onNegativeClick: () => {
        checkVideoRepaintStoryBoard(callback)
      }
    })
    callback(false)
  }else {
    checkVideoRepaintStoryBoard(callback)
  }
}


const checkVideoRepaintStoryBoard= (callback: any) =>{
  storyController.checkVideoRepaintStoryBoard(props.story.id,"1").then(res => {
    if (res.code === 200) {
      callback(true)
    } else {
      message.error(res.data);
      callback(false)
    }
  })
}



// 分镜合并
const boardTextMerge = async (type:string) =>{
  if(type==='merge') {
    videoTextListMerge.value = []
    const endTime = videoTextList.value[videoTextList.value.length - 1].endTime
    const newBoardsLength = Math.ceil(endTime / mergeSeconds.value)
    for (let i = 0; i < newBoardsLength; i++) {
      const startTime = i * mergeSeconds.value
      const endTime = (i + 1) * mergeSeconds.value
      const timeZoneBoards = getBoardByTimeZone(startTime, endTime)
      if(timeZoneBoards != null && timeZoneBoards.length === 0){
        continue
      }
      const startTimeNew = timeZoneBoards[0].startTime
      const endTimeNew = timeZoneBoards[timeZoneBoards.length - 1].endTime
      const content = timeZoneBoards.map(item => item.content).join(mergeString.value)
      const board = {
        chapterId: props.story.id,
        startTime: startTimeNew,
        endTime: endTimeNew,
        content: content
      }
      videoTextListMerge.value.push(board)
    }
  }else{
     Object.assign(videoTextListMerge.value , videoTextList.value)
  }
  isChange.value = true
}


const initialization = () => {
  initializationLoading.value = true
  let storyBoardList = []
  videoTextListMerge.value.forEach((item: any, index) => {
    let storyBoard = {
      id: "",
      orderNum: index,
      chapterId: props.story.id,
      content: item.content,
      startTime: item.startTime,
      endTime: item.endTime,
      examplePic: ''
    }
    storyBoardList.push(storyBoard)
  })
  const data = {
    storyBoardList: storyBoardList
  }
  storyBoardController.initializationVideoStoryBoard(data).then(res => {
    if (res.code === 200) {
      message.success(res.msg)
      isChange.value = false
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    initializationLoading.value = false
  })
}

const getBoardByTimeZone = (startTime:number,endTime:number) =>{
  let list: any[] = []
  videoTextList.value.forEach((item,index) => {
    const startTimeBoard = Math.floor(item.startTime)
    const endTimeBoard = Math.floor(item.endTime)
    console.log(startTimeBoard,endTimeBoard)
    if(startTimeBoard >= startTime &&  endTimeBoard <= endTime){
      list.push(item)
    }
  })
  return list
}

defineExpose({
  nextStep
})

</script>
